package com.example.port.Controller;

import com.example.port.dto.ApiResponse;
import com.example.port.entity.StorageRecord;
import com.example.port.service.StorageRecordService;
import com.example.port.service.CargoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/storage-records")
public class StorageRecordController {
    
    private final StorageRecordService storageRecordService;
    private final CargoService cargoService;
    
    @Autowired
    public StorageRecordController(StorageRecordService storageRecordService, CargoService cargoService) {
        this.storageRecordService = storageRecordService;
        this.cargoService = cargoService;
    }
    
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<Integer> createStorageRecord(@RequestBody StorageRecord record) {
        int result = storageRecordService.insertStorageRecord(record);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "创建仓储记录失败");
    }
    
    @GetMapping
    public ApiResponse<List<StorageRecord>> getAllStorageRecords() {
        List<StorageRecord> storageRecords = storageRecordService.getAllStorageRecords();
        return ApiResponse.success(storageRecords);
    }
    
    @GetMapping("/{recordId}")
    public ApiResponse<StorageRecord> getStorageRecordById(@PathVariable Long recordId) {
        StorageRecord record = storageRecordService.getStorageRecordById(recordId);
        if (record != null) {
            return ApiResponse.success(record);
        }
        return ApiResponse.error(404, "仓储记录不存在");
    }
    
    @PutMapping("/{recordId}")
    public ApiResponse<Integer> updateStorageRecord(@PathVariable Long recordId, @RequestBody StorageRecord record) {
        record.setRecordId(recordId);
        int result = storageRecordService.updateStorageRecord(record);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "更新仓储记录失败");
    }
    
    @DeleteMapping("/{recordId}")
    public ApiResponse<Integer> deleteStorageRecord(@PathVariable Long recordId) {
        int result = storageRecordService.deleteStorageRecord(recordId);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "删除仓储记录失败");
    }
    
    @GetMapping("/cargo/{cargoId}")
    public ApiResponse<List<StorageRecord>> getStorageRecordsByCargoId(@PathVariable Integer cargoId) {
        List<StorageRecord> records = storageRecordService.getStorageRecordsByCargoId(cargoId);
        return ApiResponse.success(records);
    }
} 
